<template slot-scope="scope">
  <el-container class="whole">
    <el-header
      height="50px"
      style="
        background-color: #313131;
        color: white;
        font-size: 30px;
        line-height: 50px;
      "
      >求索问卷--吾将上下而求索</el-header
    >
    <el-main class="body" v-if="isLock === false">
      <div class="qrcode">
        <vue-qr :text="link" :size="70" :margin="5"></vue-qr>
      </div>
      <div class="date">
        <div>发布者: {{ survey.author }}</div>
        <div>发布时间: {{ pulishTime }}</div>
        <div v-if="survey.deadline != undefined">
          截止时间: {{ deadlineTime }}
        </div>
      </div>
      <div class="title">{{ survey.title }}</div>
      <div class="description">{{ survey.description }}</div>
      <div v-if="finish === false">
        <div
          v-for="(item, index) in survey.questions"
          :key="index"
          style="border-top: 1px solid #e0e0e0; padding-bottom: 15px"
        >
          <div
            style="
              margin: 0 auto;
              width: 80%;
              padding-top: 30px;
              padding-bottom: 10px;
            "
          >
            <span v-if="!survey.numHidden">第 {{ index + 1 }} 题 </span>(<span
              v-if="item.type === 0"
              >单选</span
            >
            <span v-if="item.type === 1">多选</span>
            <span v-if="item.type === 3">填空</span>
            <span v-if="item.type === 2">评分</span>
            <span v-if="item.type === 5">报名</span>
            <span v-if="item.type === 4">投票</span>
            <span v-if="item.type === 6">定位</span>
            <span v-if="[1, 4, 5].indexOf(item.type) >= 0"
              ><span v-if="item.propJson.min == item.propJson.max">{{
                item.propJson.min
              }}</span
              ><span v-else
                >{{ item.propJson.min }}~{{ item.propJson.max }}</span
              >个</span
            >)
            <span v-if="item.required === true" style="color: red">(必选)</span>
          </div>
          <div class="questions">{{ item.stem }}</div>
          <div
            class="questions_description"
            style="color: #999999; font-size: 10px"
          >
            {{ item.description }}
          </div>
          <div v-if="item.type === 0" class="questions">
            <el-radio-group v-model="answer['' + item.num]">
              <el-radio
                v-for="(choice, choice_index) in item.propJson.options"
                :key="choice_index"
                style="display: block; margin: 25px 0"
                :label="choice_index"
                >{{ item.propJson.options[choice_index] }}</el-radio
              >
            </el-radio-group>
          </div>
          <div v-if="item.type === 1 || item.type === 4" class="questions">
            <el-checkbox-group v-model="answer['' + item.num]">
              <el-checkbox
                v-for="(choice, choice_index) in item.propJson.options"
                :key="choice_index"
                style="display: block; margin: 25px 0"
                :label="choice_index"
                >{{ item.propJson.options[choice_index] }}
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="item.type === 3" class="questions">
            <el-input
              v-model="answer['' + item.num]"
              type="textarea"
              autosize
              placeholder="在这里填写回答..."
              style="margin: 25px 0"
            ></el-input>
          </div>
          <div v-if="item.type === 2" class="questions">
            <el-rate
              style="margin: 25px 0"
              v-model="answer['' + item.num]"
            ></el-rate>
          </div>
          <div v-if="item.type === 5" class="questions">
            <el-checkbox-group v-model="answer['' + item.num]">
              <el-checkbox
                v-for="(choice, choice_index) in item.propJson.options"
                :key="choice_index"
                style="display: block; margin: 25px 0; width: 420px"
                :label="choice_index"
                :disabled="
                  item.propJson.limit[choice_index] -
                    item.propJson.num[choice_index] ===
                  0
                "
                >{{ item.propJson.options[choice_index] }}
                <div style="display: inline-block; padding: 0 0 0 100px">
                  <span v-if="item.propJson.limit[choice_index] == 0"
                    >无人数限制</span
                  ><span v-else
                    >总人数:{{ item.propJson.limit[choice_index] }} 剩余人数:{{
                      item.propJson.limit[choice_index] -
                      item.propJson.num[choice_index]
                    }}</span
                  >
                </div>
              </el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="item.type === 6" class="questions">
            <div style="margin: 25px 0">
              <el-input
                style="display: inline-block; width: 400px"
                v-model="answer['' + item.num][2]"
                disabled
              ></el-input>
              <el-button @click="Locate(item.num)">点击获取当前位置</el-button>
            </div>
          </div>
        </div>
        <div style="text-align: center; padding: 30px 0">
          <el-button type="primary" @click="check" style="width: 120px"
            >提 交</el-button
          >
        </div>
      </div>
      <div v-else>
        <div v-if="voteIndex">
          <div
            style="text-align: center"
            v-for="(vote, index) in voteData"
            :key="index"
          >
            <h3>投票: {{ voteStem[index] }}</h3>
            <el-table
              :data="vote"
              style="width: 80%; margin: 0 auto"
              :show-summary="true"
            >
              <el-table-column
                prop="select"
                label="选项"
                width="250"
              ></el-table-column>
              <el-table-column prop="num" label="小计"></el-table-column>
              <el-table-column prop="rate" label="比例"></el-table-column>
            </el-table>
          </div>
        </div>
        <div
          style="
            text-align: center;
            font-size: 30px;
            margin-top: 130px;
            margin-bottom: 20px;
          "
        >
          感谢你的填写!
        </div>
        <div style="text-align: center">
          <el-button @click="toMainpage" style="width: 120px">主 页</el-button>
        </div>
      </div>
    </el-main>
    <el-dialog
      :visible.sync="isLock"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      title="提示"
    >
      <div style="font-size: 20px; line-height: 40px">
        该问卷为非公开问卷,请输入口令后填写 :
      </div>
      <el-input v-model="password" type="password"></el-input>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="unlock" @keyup.enter.native="unlock"
          >确 认</el-button
        >
      </div>
    </el-dialog>
    <el-dialog :visible.sync="isLocated" title="提示">
      <div style="font-size: 20px; line-height: 40px">
        该网站请求获取你的位置信息...
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getLocate">确 认</el-button>
        <el-button @click="isLocated = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-container>
</template>

<script>
import { MapLoader } from "../assets/locate";
export default {
  data() {
    return {
      pulishTime: "",
      deadlineTime: "",
      link: "",
      isLock: false,
      isLocated: false,
      locateIndex: "",
      voteIndex: false,
      finish: false,
      password: "",
      sid: "",
      survey: {},
      answer: {},
      vote_q: [],
      enroll_q: [],
      voteStem: [],
      voteData: [],
    };
  },
  methods: {
    unlock() {
      this.$http
        .get("/survey/" + this.sid + "?code=" + this.password)
        .then((res) => {
          this.answer = this.outputAnswerSheet(this.clone(res.data.questions));
          this.survey = this.clone(res.data);
          for (var i = 0; i < this.survey.questions.length; i++) {
            this.survey.questions[i].propJson = JSON.parse(
              this.survey.questions[i].propJson
            );
            if (this.survey.questions[i].type === 4)
              this.vote_q.push(this.survey.questions[i]);
            if (this.survey.questions[i].type === 5)
              this.enroll_q.push(this.survey.questions[i]);
          }
          if (this.survey.mixed)
            this.survey.questions = this.mixed(this.survey.questions);
          this.init_e();
          this.pulishTime = this.convertTime(this.survey.pubTime);
          this.deadlineTime = this.convertTime(this.survey.deadline);
          this.isLock = false;
        })
        .catch((err) => {
          if (err.response.status == 406) {
            alert("口令错误!");
            this.password = "";
          } else {
            alert("网络错误,请稍后再试!");
            this.$router.push("/introduction");
          }
        });
    },
    outputAnswerSheet(questions) {
      var answerSheet = {};
      for (var i = 0; i < questions.length; i++) {
        if ([1, 4, 5, 6].indexOf(questions[i].type) >= 0) {
          answerSheet["" + questions[i].num] = [];
        } else if (questions[i].type == 0) {
          answerSheet["" + questions[i].num] = null;
        } else if (questions[i].type == 2) {
          answerSheet["" + questions[i].num] = 0;
        } else if (questions[i].type == 3) {
          answerSheet["" + questions[i].num] = null;
        }
      }
      // console.log(answerSheet);
      return answerSheet;
    },
    check() {
      var unfinish = [];
      var overmax = [];
      var belowmin = [];
      var q = this.survey.questions;
      for (var i = 0; i < q.length; i++) {
        if (q[i].type == 0 && q[i].required && this.answer[q[i].num] == null)
          unfinish.push(i + 1);
        else if (q[i].type == 2 && q[i].required && this.answer[q[i].num] == 0)
          unfinish.push(i + 1);
        else if (q[i].type == 3 && q[i].required && !this.answer[q[i].num])
          unfinish.push(i + 1);
        else if (
          [1, 4, 5, 6].indexOf(q[i].type) >= 0 &&
          q[i].required &&
          this.answer[q[i].num].length == 0
        )
          unfinish.push(i + 1);
        else if ([1, 4, 5].indexOf(q[i].type) >= 0 && q[i].required) {
          if (this.answer[q[i].num].length > q[i].propJson.max) {
            overmax.push(i + 1);
          } else if (this.answer[q[i].num].length < q[i].propJson.min) {
            belowmin.push(i + 1);
          }
        }
      }
      if (unfinish.length > 0 || overmax.length > 0 || belowmin.length > 0) {
        var str = "";
        if (unfinish.length > 0)
          str += "必选题有第" + unfinish.toString() + "题未填写!";
        if (overmax.length > 0)
          str += "第" + overmax.toString() + "题多选题选项个数超过要求个数!";
        if (belowmin.length > 0)
          str += "第" + belowmin.toString() + "题多选题选项个数少于要求个数!";
        alert(str);
      } else {
        // alert(JSON.stringify(this.answer));
        // console.log(encodeURI(JSON.stringify(this.answer)));
        this.submit();
      }
    },
    submit() {
      var str = "";
      if (this.$store.state.isLogin === true) {
        str += "&uid=" + sessionStorage.getItem("uid");
      }
      this.$http
        .post(
          "/survey/ans?sid=" +
            this.sid +
            "&answerJson=" +
            encodeURI(JSON.stringify(this.answer)) +
            str
        )
        .then((res) => {
          // console.log(res);
          this.finish = true;
        })
        .catch((err) => {
          if (err.response.status == 403) {
            alert("问卷未开放或已截止!");
          } else {
            alert("网络错误,请稍后再试!");
          }
        });
      if (this.vote_q.length > 0) {
        setTimeout(this.get_voteIndex, 100);
      }
    },
    get_voteIndex() {
      //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>获取投票数据
      var vote = [];
      for (var i = 0; i < this.vote_q.length; i++) {
        vote.push(this.vote_q[i].qid);
      }
      this.$http
        .post("/stat/question?sid=" + this.sid, vote)
        .then((res) => {
          this.processingVoteIndex(this.clone(res.data));
        })
        .catch((err) => {
          if (err.response.status === 401) {
            this.$message.error("用户未登录!");
          } else {
            this.$message.error("网络错误,请稍后再试!");
          }
        });
    },
    processingVoteIndex(data) {
      for (var i = 0; i < data.length; i++) {
        data[i].propJson = JSON.parse(data[i].propJson);
        data[i].statJson = JSON.parse(data[i].statJson);
      }
      // console.log(data);
      this.voteData = [];
      for (var i = 0; i < data.length; i++) {
        var sum = 0;
        this.voteStem.push(data[i].stem);
        data[i].statJson.num.forEach((element) => {
          sum += element;
        });
        // console.log(sum);
        var item = [];
        for (var j = 0; j < data[i].propJson.options.length; j++) {
          var index = {};
          index["select"] = data[i].propJson.options[j];
          index["num"] = data[i].statJson.num[j];
          index["rate"] = ((index["num"] / sum) * 100).toFixed(2) + "%";
          item.push(index);
        }
        this.voteData.push(item);
      }
      // console.log(this.voteData);
      this.voteIndex = true;
    },
    Locate(index) {
      this.locateIndex = index;
      this.isLocated = true;
    },
    getLocate() {
      var index = this.locateIndex;
      this.isLocated = false;
      MapLoader().then((res) => {
        // console.log(res);
        if (res == null) {
          this.$message.error("获取位置失败,请稍后再试!");
        } else {
          this.answer[index].push(this.clone(res.position["R"]));
          this.answer[index].push(this.clone(res.position["Q"]));
          this.answer[index].push(this.clone(res.formattedAddress));
        }
      });
    },
    convertTime(timestampe) {
      var time = new Date(timestampe);
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      return (
        y +
        "-" +
        this.add0(m) +
        "-" +
        this.add0(d) +
        "-" +
        this.add0(h) +
        ":" +
        this.add0(mm) +
        ":" +
        this.add0(s)
      );
    },
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
    toMainpage() {
      this.$router.push("/introduction");
    },
    clone(obj) {
      return JSON.parse(JSON.stringify(obj));
    },
    init_e() {
      for (var i = 0; i < this.enroll_q.length; i++) {
        if (this.enroll_q[i].propJson.num == undefined)
          this.enroll_q[i].propJson.num = Array(
            this.enroll_q[i].propJson.options.length
          ).fill(0);
      }
    },
    mixed(arr) {
      for (var i = 0; i < arr.length; i++) {
        var iRand = parseInt(arr.length * Math.random());
        var temp = arr[i];
        arr[i] = arr[iRand];
        arr[iRand] = temp;
      }
      return arr;
    },
  },
  created() {
    var id = this.$route.params.id;
    this.sid = id;
    this.link = "http://106.12.141.103:8080/index.html#/question/" + this.sid;
    //>>>>>>>>>>>>>>>>>>>>>>>>>>>>后台获取问卷信息
    this.survey = {
      author: "测试人员",
      title: "测试问卷",
      description: "这是描述",
      code: "",
      creTime: 1629539507000,
      pubTime: 1629539626000,
      deadline: 1630403611000,
      status: 1,
      ansNum: 0,
      questions: [
        {
          type: 3,
          stem: "你觉得北航怎么样?",
          description: "",
          required: false,
          propJson: { num: 1 },
        },
      ],
    };
    this.$http
      .get("/survey/" + id)
      .then((res) => {
        this.answer = this.outputAnswerSheet(this.clone(res.data.questions));
        // console.log(this.answer);
        this.survey = this.clone(res.data);
        // console.log(this.survey);
        for (var i = 0; i < this.survey.questions.length; i++) {
          this.survey.questions[i].propJson = JSON.parse(
            this.survey.questions[i].propJson
          );
          if (this.survey.questions[i].type === 4)
            this.vote_q.push(this.survey.questions[i]);
          if (this.survey.questions[i].type === 5)
            this.enroll_q.push(this.survey.questions[i]);
        }
        if (this.survey.mixed)
          this.survey.questions = this.mixed(this.survey.questions);
        this.init_e();
        this.pulishTime = this.convertTime(this.survey.pubTime);
        this.deadlineTime = this.convertTime(this.survey.deadline);
        this.pulishTime = this.convertTime(this.survey.pubTime);
        this.deadlineTime = this.convertTime(this.survey.deadline);
        console.log(this.survey);
      })
      .catch((err) => {
        console.log(err);
        if (err.response.status === 403) {
          alert("本问卷暂未开启或已截止,即将跳转至其他页面...");
          this.$router.push("/introduction");
        } else if (err.response.status === 406) {
          console.log("有密码");
          this.isLock = true;
        } else {
          alert("问卷获取失败,请稍后再试!");
          this.$router.push("/introduction");
        }
      });
    // console.log(this.survey);
  },
};
</script>


<style lang="less" scoped>
.whole {
  height: 100%;
  width: 100%;
  background-color: #f5f5f5;
}
.body {
  height: 100%;
  width: 50%;
  margin: 0 auto;
  background-color: #fff;
  overflow: auto;
}
.title {
  text-align: center;
  padding: 30px 0 20px 0;
  font-size: 30px;
  max-width: 40%;
  margin: 0 auto;
}
.qrcode {
  float: left;
}
.date {
  float: right;
  font-size: 12px;
  padding-right: 10px;
  padding-top: 10px;
  color: #5a5a5a;
}
.description {
  text-align: center;
  font-size: 15px;
  max-width: 60%;
  margin: 0 auto;
  padding-bottom: 20px;
}
.questions {
  width: 80%;
  margin: 0 auto;
}
.questions_description {
  width: 80%;
  margin: 5px auto;
}
</style>